<?php
include("/var/www/html/new/com.inc.php");
include("/var/www/html/alipay/alipay.config.php");
include("/var/www/html/alipay/lib/alipay_notify.class.php");
include("/var/www/html/new/d/class/OrderRecord.php");

define('ACTION_MONEY_ADD',0);
define('ACTION_MONEY_CUT',1);
define('ERROR_LOG', '/var/www/html/new/d/logs/alipay_qr/err_log_'.date('ymd').'.txt');
define('OK_LOG', '/var/www/html/new/d/logs/alipay_qr/log_'.date('ymd').'.txt');
define('MACHINE_LOG', '/var/www/html/new/d/logs/alipay_qr/machine_'.date('ymd').'.txt');

write_logs(json_encode($_POST), OK_LOG);
//计算得出通知验证结果
$alipayNotify = new AlipayNotify($alipay_config);
$verify_result = $alipayNotify->verifyNotify();



if($verify_result) {//验证成功
    $notify_data    = (array)simplexml_load_string($_POST['notify_data']);
    $out_trade_no   = $notify_data['out_trade_no'];// 商户订单号
    $trade_no       = $notify_data['trade_no']; // 支付宝交易号
    $trade_status   = $notify_data['trade_status'];// 交易状态
    write_logs('验证成功', OK_LOG);

    if($notify_data['trade_status'] == 'TRADE_FINISHED') {
        write_logs("1:$trade_no:$out_trade_no:$trade_status", ERROR_LOG);
    }
    else if ($notify_data['trade_status'] == 'TRADE_SUCCESS') {
        $total_fee = floatval($notify_data['total_fee']) * 100;
        //判断该笔订单是否在商户网站中已经做过处理
        $s = new SoapClient(null,array(
                "location" => "http://localhost/open/openService/pft_insideMX.php",
                "uri" => "www.16u.com?ac_16u={$GLOBALS['_ac']}|pw_16u={$GLOBALS['_pw']}|auth_16u=true")
        );
        $str="select id from pft_alipay_rec where out_trade_no='$out_trade_no' LIMIT 1";
        $GLOBALS['le']->query($str);
        if (!$GLOBALS['le']->fetch_assoc()) {
            $str=<<<SQL
INSERT pft_alipay_rec set out_trade_no='$out_trade_no',status=1,
dtime=now(),`trade_no`='$trade_no',buyer_email='{$notify_data['buyer_email']}',
subject='扫码支付-{$notify_data['subject']}订单',total_fee='$total_fee'
SQL;
        }
        else {
            $str=<<<SQL
update pft_alipay_rec set status=1,dtime=now(),`trade_no`='$trade_no'
WHERE out_trade_no='$out_trade_no' limit 1
SQL;
        }
        write_logs($str, ERROR_LOG);
        $GLOBALS['le']->query($str);

        $or=new OrderRecord($out_trade_no, $s);
        $orders=$or->info();
        total_fee($orders);
        $aid = (string)$orders['mainOrder']->UUaid;
        $mid = (string)$orders['mainOrder']->UUmid;
        fenRun($s,$out_trade_no,$total_fee,$orders,true);

        include '/var/www/html/new/d/class/OrderSmsManual.class.php';
        $smsManual  = new \PFT\SMS\OrderSmsManual($s);
        $ret = $smsManual->SendByOrderInfo($orders);
        if ($ret!=100) {
            write_logs("短信发送失败|订单号[$out_trade_no]|返回代码[$ret]", ERROR_LOG);
        } else {
            write_logs("短信发送成功|订单号[$out_trade_no]|返回代码[$ret]", OK_LOG);
        }

        $ret = $s->Mod_Order_Status($out_trade_no,1,1);
        write_logs("更新订单状态|订单号[$out_trade_no]|返回代码[$ret]", OK_LOG);

        //闸机
//        $lhs_array = array(
//            'ip'            => '192.168.1.145',
//            'command'       => 1,
//            'personcount'   => (int)$orders['mainOrder']->UUtnum
//        );
//        $json = Gate_post($lhs_array);
//        write_logs($json, MACHINE_LOG);
//        $arr_result= json_decode($json);
//        if ($arr_result->code==1) {
//            //success
//            $ret = $soap->Terminal_Check_In(
//                (string)$orders['mainOrder']->UUsalerid,
//                (string)$orders['mainOrder']->UUcode
//            );
//            if (!is_numeric($ret)) {
//                write_logs("验票成功.订单号[$out_trade_no]", OK_LOG);
//            } else {
//                write_logs("验票失败.订单号[$out_trade_no].返回值[{$ret}]", OK_LOG);
//            }
//        } elseif ($arr_result->code==0) {
//            //fail
//            write_logs("闸机调用失败.订单号[$out_trade_no].", ERROR_LOG);
//        }
    }

    //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
    echo "success";        //请不要修改或删除
    logResult("2:$trade_no:$out_trade_no:$trade_status\n");
}
else {
    //验证失败
    echo "fail";
    write_logs("3:$trade_no:$out_trade_no:$trade_status", ERROR_LOG);
}

// 转分销分润
function fenRun($s,$ordern,$total_fee,$orders,$to_pft){

    $aid = (string)$orders['mainOrder']->UUaid;
    $mid = (string)$orders['mainOrder']->UUmid;
    $add = 0; $cut = 1;

    // 非自供产品获取结算价
    if($aid!=$mid){
        $total_money = 0;
        $pid = (string)$orders['mainOrder']->UUpid;// 产品 id
        $begintime = (string)$orders['mainOrder']->UUbegintime;// 游玩时间价格
        $account = (string)$orders['mainOrder']->UUfromt;// 游玩时间价格
        $ret = $s->Dynamic_Price_And_Storage($account,$pid,$begintime,1,0,0,$aid);
        if($ret==105||$ret==1065){
            $total_money = $total_fee;
        }else{
            $obj = simplexml_load_string($ret);
            $total_money = (string)$obj->Rec->UUsprice * (int)$orders['mainOrder']->UUtnum;
        }
        if(count($orders['childOrder']) && $orders['mainOrder']->UUp_type!='F'){
            foreach($orders['childOrder'] as $key=>$child){
                $pid = (string)$child->UUpid;// 产品 id
                $ret = $s->Dynamic_Price_And_Storage($account,$pid,$begintime,1,0,0,$aid);
                if($ret!=105 && $ret!=1065){
                    $obj = simplexml_load_string($ret);
                    $total_money += (string)$obj->Rec->UUsprice * (int)$child->UUtnum;
                }
            }
        }
    }

    if($to_pft){
        //票付通总账号加钱——2015年4月13日11:56:33林农说要添加，宝椿提供的代码
        $s->PFT_Member_Fund_Modify(1, 0, $total_fee, $add, 0,null,0, 0,$ordern);
        // 支付给了票付通，最下级供应商加钱
        $s->PFT_Member_Fund_Modify($aid, 0, $total_fee, $add, 0,null,0, 1,$ordern);
    }


    // 产品多级销售分润
    $str="select aids_money from uu_order_fx_details where orderid='$ordern' limit 1";
    $GLOBALS['le']->query($str);
    $lirun = $GLOBALS['le']->fetch_assoc();
    if ($lirun['aids_money']){

        // 子票没有记录分润，获取子票价格
        $childMenoy = array();
        if(count($orders['childOrder']) && $orders['mainOrder']->UUp_type!='F'){
            foreach($orders['childOrder'] as $key=>$child){
                $aids = explode(',',(string)$child->UUaids);
                krsort($aids);
                $aids_price = explode(',',(string)$child->UUaids_price);
                krsort($aids_price);
                foreach($aids as $k=>$et){
                    if($k==0) break;// 最后一个不用操作了
                    $childMenoy[$et]+= $aids_price[$k-1] * (string)$child->UUtnum;
                }
            }
        }
        // 主订单的 aids
        $main_aids = explode(',',(string)$orders['mainOrder']->UUaids);
        $aids_money = unserialize($lirun['aids_money']);
        $opID = 0;
        foreach($aids_money as $row){
            $fid=$row[0];
            $action = ($row[2]==0) ? $cut : $add;//0减少,1增加和接口相反
            $Mmoney=$row[3];
            if($action==0){ // 加钱
                $ks = array_search($fid,$main_aids);
                $ks = $ks+1;
                $Mmoney += isset($childMenoy[$main_aids[$ks]]) ? $childMenoy[$main_aids[$ks]]:0;
            }else{
                $Mmoney += isset($childMenoy[$fid]) ? $childMenoy[$fid]:0;
            }

            if($row[1]==0){//信用额度
                $dmode = 1;
                $res = $s->PFT_Member_Fund_Modify($fid,$opID,$Mmoney,$action,$dmode,$row[4],0,2,$ordern);
            }else{//资金
                $dmode = 0;
                $res = $s->PFT_Member_Fund_Modify($fid,$opID,$Mmoney,$action,$dmode,NULL,0,0,$ordern);
            }
        }
    }
    return $total_money;// 返回上级利润
}

// 获取订单总价格，以分为单位
function total_fee($orders){
    $total_fee = 0;
    $aid = (string)$orders['mainOrder']->UUaid;
    $mid = (string)$orders['mainOrder']->UUmid;

    $total_fee=((string)$orders['mainOrder']->UUtprice * (string)$orders['mainOrder']->UUtnum);
    $ordernum = (string)$orders['mainOrder']->UUordernum;
    $str=<<<SQL
insert pft_member_alipay set fid=$mid,orderid='$ordernum',
total_fee='$total_fee',money='$total_fee',ali_account='',rectime=now(),
dtype=0,daction=1
SQL;
    $GLOBALS['le']->query($str);

    // 加上非套票的子票价格
    if(count($orders['childOrder']) && $orders['mainOrder']->UUp_type!='F'){
        foreach($orders['childOrder'] as $key=>$child){
            $tmp = (int)$child->UUtprice * (int)$child->UUtnum;
            $total_fee+=$tmp;
            $ordernum = (string)$child->UUordernum;
            $str=<<<SQL
INSERT pft_member_alipay set fid=$mid,orderid='$ordernum',
total_fee='$tmp',money='$tmp',ali_account='',rectime=now(),dtype=0,daction=1
SQL;
            $GLOBALS['le']->query($str);
        }
    }
    return $total_fee;
}


function write_logs($txt,$file='/var/www/html/alipay/new_log.txt'){
    $fp = fopen($file,"a");
    flock($fp, LOCK_EX);
    fwrite($fp,date("Y-m-d H:i:s").":".$txt."\n");
    flock($fp, LOCK_UN);
    fclose($fp);
}

function Gate_post($array){
    $o="";
    foreach ($array as $k=>$v){
        $o.= "$k=".urlencode($v)."&";
    }
    $url='http://jtsvn.eicp.net:8077/et/ticketchecking/opengate/cmd.do';

    $post_data=substr($o,0,-1);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    // return curl_exec($ch);
    $result = curl_exec($ch);
    if (!$result) {
        return curl_error($ch);
    }else {
        return $result;
    }
}
function ticket_check($personcount, $machine_ip='192.168.1.145', $cmd=1 )
{
    ///et/ticketchecking/opengate/cmd.do
    $url = 'http://110.90.48.131:8077/et/ticketchecking/opengate/cmd.do';
    $para = array('ip'=>$machine_ip, 'command'=>$cmd, 'personcount'=>$personcount);
    $json_result = getHttpResponsePOST($url, '', $para);
    write_logs($json_result, MACHINE_LOG);
    return json_decode($json_result);
//    return $arr_result;
}